<template>
  <Dialog v-model="visible" title="数据权限" width="800">
    <el-form ref="formRef" v-loading="loading" :model="form">
      <el-form-item label="角色名称">
        <el-tag>{{ form.name }}</el-tag>
      </el-form-item>
      <el-form-item label="权限范围">
        <el-select v-model="form.dataScope">
          <el-option
            v-for="item in dataScopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="loading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="DataPermissionForm" setup>
import * as Api from '@/api/userCenter/auth/role'
import * as PermissionApi from '@/api/userCenter/auth/permission'

const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const form = ref({
  id: 0,
  name: '',
  code: '',
  dataScope: undefined,
  dataScopeDeptIds: []
})
const formRef = ref() // 表单 Ref
const treeRef = ref() // 菜单树组件 Ref
const treeNodeAll = ref(false) // 全选/全不选
const checkStrictly = ref(true) // 是否严格模式,即父子不关联
const dataScopeOptions = ref([
  {
    label: '全部数据',
    value: 'global'
  },
  { label: '与我相关的数据(我创建或指派给我)', value: 'locale' }
])

/** 打开弹窗 */
const open = async (row: Api.Model) => {
  visible.value = true
  resetForm()
  // 设置数据
  form.value.id = row.id
  form.value.name = row.name
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {
  loading.value = true
  try {
    const data = {
      roleId: form.value.id,
      dataScope: form.value.dataScope
    }
    await PermissionApi.assignRoleDataScope(data)
    message.success(`操作成功`)
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('提交表单失败')
  } finally {
    loading.value = false
  }
}

/** 重 置表单 */
const resetForm = () => {
  // 重 置选项
  treeNodeAll.value = false
  checkStrictly.value = true
  // 重 置表单
  form.value = {
    id: 0,
    name: '',
    code: '',
    dataScope: undefined
  }
  treeRef.value?.setCheckedNodes([])
  formRef.value?.resetFields()
}
</script>
